package com.youtui.manager.interceptor;

import java.lang.reflect.Method;
import java.util.Date;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import com.youtui.manager.model.Opter;

/** mapper方法过滤aop,添加额外参数 */
public class DataEditInterceptor implements MethodInterceptor {

	@Override
	public Object invoke(MethodInvocation methodInvocation) throws Throwable {
		Subject subject = SecurityUtils.getSubject();
		Opter opter = (Opter) subject.getPrincipal();
		Long userId = null;
		if (opter != null) {
			userId = opter.getId();
		}
		Method method = methodInvocation.getMethod();
		String methodName = method.getName();
		Object[] args = methodInvocation.getArguments();
		for (Object obj : args) {
			Method[] methods = obj.getClass().getMethods();
			if (methodName.contains("update")) {
				for (Method m : methods) {
					if (m.getName().equalsIgnoreCase("setModifytime")) {
						m.invoke(obj, new Date());
					}
					if (m.getName().equalsIgnoreCase("setModifyer")) {
						m.invoke(obj, userId);
					}
				}
			}
			if (methodName.contains("insert")) {
				for (Method m : methods) {
					if (m.getName().equalsIgnoreCase("setCreatetime")) {
						m.invoke(obj, new Date());
					}
					if (m.getName().equalsIgnoreCase("setCreater")) {
						m.invoke(obj, userId);
					}
				}
			}
			if (methodName.contains("delete")) {
				for (Method m : methods) {
					if (m.getName().equalsIgnoreCase("setDeltime")) {
						m.invoke(obj, new Date());
					}
					if (m.getName().equalsIgnoreCase("setDeler")) {
						m.invoke(obj, userId);
					}
				}
			}
		}
		return methodInvocation.proceed();
	}
}
